import webapp2
from Model import *
import datetime
from google.appengine.ext import ndb
from google.appengine.api import memcache
import logging



class RaceFinishedHandler(webapp2.RequestHandler):
    
    def post(self):
        user_key = ndb.Key('User',int(self.request.POST.get('userID')))
        user = user_key.get()  # urlsafe = self.request.POST['key']))
        user.Grade = user.Grade + int(self.request.POST.get('score'))
        user.put()

        race_id = int(self.request.POST.get('raceID'))
        race_key = ndb.Key('Race', race_id)
        race = race_key.get()

        race_history = RaceHistory.query(ndb.AND(RaceHistory.Grade == -1, RaceHistory.Racer == user_key)).get()
        race_history.Grade = int(self.request.POST.get('score'))
        race_history.RaceDate = race.StartTime
        logging.debug("update RaceHistory garade and RaceDate")
        race_history.put()


        #self.response.out.write(json.dumps({"estimatedTime" : race.EstimatedTime}))



    def get(self):
        race_key = ndb.Key('Race', int(self.request.GET['race']))
        self.response.out.write(json.dumps(finishedRacers(race_key)))

def finishedRacers(race):
    allParticipants = CurrentStats.query.filter(ndb.AND((CurrentStats.Race == race), (CurrentStats.Status==RacerStatus.Finished))).order(CurrentStats.ActualDistance)
    return [{'key': participant.key.id(), 'race': participant.Race.id(), 'racer': participant.Racer.id(), 'speed': participant.Speed, 'name': participant.Name,
             'actualdistance': participant.ActualDistance} for participant in allParticipants]

